﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Code.Models;
using Code.Commen;
using Code.BLL;
using System.Threading;

namespace QianBuo.Lottery.Server
{
    internal class CheckIssue
    {
        #region 私有成员
        IssueManage IM = new IssueManage();
        LotteryManage LM = new LotteryManage();
        /// <summary>
        /// 日志记录
        /// </summary>
        private log4net.ILog Log = Code.Commen.Log.GetLog("Server.CheckIssue");
        private Thread _Thread;
        private int State=0;
        private static CheckIssue _CheckIssue;
        /// <summary>
        /// 获取当前的期号管理对象
        /// </summary>
        public static CheckIssue Current 
        {
            get 
            {
                if (_CheckIssue == null)
                    _CheckIssue = new CheckIssue();
                return _CheckIssue;
            }
        }
        #endregion

        #region 构造方法
        private CheckIssue()
        {

        }
        #endregion

        #region 公有方法

        public void Rrn()
        {
            if (State == 1)
                return;
            State = 1;
            _Thread = new Thread(new ThreadStart(Do));
            _Thread.Name = "CheckIssue";
            _Thread.Start();
        }
        public void Exit()
        {
            State = 2;
        }
        public void Exit(bool now)
        {
            State = 2;
            if (now)
                try { _Thread.Abort(); }
                catch { }
        }
        private void Do()
        {
            do
            {
                if (State != 1)
                    return;
                if (Thread.CurrentThread.Name == "CheckIssue")
                {
                    foreach (var item in CacheManage.Lottery.Values)
                    {
                        if (item.AutoAddIssue < 1)
                            continue;

                        int num = IM.AddIssue((LotteryType)item.ID, DateTime.Now.AddDays(-1).Date, item.AutoAddIssue+1);
                        if (num < 0)
                        {
                            if (Log.IsInfoEnabled)
                                Log.Info(item.Alias + "增加期号出错！");
                            if (Log.IsWarnEnabled)
                                Log.Warn(item.Alias + "增加期号出错！");
                            if (Log.IsDebugEnabled)
                                Log.Info(item.Alias + "增加期号出错！");
                        }
                    }

                    if (State != 1)
                        return;
                    TimeSpan wait = DateTime.Now.Date.AddDays(1) - DateTime.Now;
                    Thread.Sleep(wait);
                }
            } while (true);
        }

        #endregion
    }
}
